package cn.tedu.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AccessFilter extends ZuulFilter {
//指定过滤器类型，"pre" ,"routes","post","error"
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
//指定过滤器添加位置序号
    @Override
    public int filterOrder() {
        return 6;
    }

    @Override
    public boolean shouldFilter() {
//        获得正在调用的服务ID
        RequestContext requestContext=RequestContext.getCurrentContext();
        String serviced=(String) requestContext.get(FilterConstants.SERVICE_ID_KEY);

        return "item-service".equalsIgnoreCase(serviced);
    }

    @Override
    public Object run() throws ZuulException {
//        http://localhost:3001/item-service/...?token=

//        得到request对象
        RequestContext requestContext=RequestContext.getCurrentContext();
        HttpServletRequest request=requestContext.getRequest();
//        判断是否有token参数，有则正常，无则返回错误结果
        String token=request.getParameter("token");
        if (StringUtils.isBlank(token)){
            requestContext.setSendZuulResponse(false);
            String json= JsonResult.err().code(JsonResult.NOT_LOGIN).msg("no login").toString();
            requestContext.addZuulResponseHeader("Content-Type", "application/json;charset=UTF-8");
            requestContext.setResponseBody(json);
        }
        return null;

    }
}
